import * as machineService from '../../services/resource/machineService';
import { message } from 'antd';
import config from '../../config/config';
import {getSystemMonitorData} from "../../services/resource/machineService";

export default {
  namespace: "machineModel",
  state: {
    machineLoading: false,
    total: 0,
    currentPage: 1,
    pageSize: config.PAGE_SIZE,
    machineList: [],
    machineModalVisible: false,
    operateType: "add",
    machineInfoData: null,
    saveLoading: false,
    machineInstanceRecord: {},
    machineLineData: []
  },
  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload }
    },
  },
  effects: {
    *getMachineList({ payload: params }, { select, call, put }) {
      yield put({ type: "updateState", payload: { machineLoading: true }});
      params.currentPage = params.currentPage ? params.currentPage : 1;
      params.pageSize = params.pageSize ? params.pageSize : config.PAGE_SIZE;
      const res = yield call(machineService.getMachineList, { ...params });
      if (res.code == "200") {
        yield put({
          type: "updateState",
          payload: { machineList: res.data.records, total: res.data.total,
            currentPag: params.currentPage, pageSize: params.pageSize }
        });
      }
      yield put({ type: "updateState", payload: { machineLoading: false }});
    },

    *downloadTemplate({ payload: params }, { select, call, put }) {
      const res = yield call(machineService.downloadTemplate, { type: "machine" });
      if (res.code != "200") {
        message.error(res.message)
      }
    },

    *onRefresh({ payload: params }, { select, call, put }) {
      const res = yield call(machineService.refreshMonitor, params);
      if (res.code == "200") {
        yield put({ type: "getMachineList", payload: {}});
        console.log("刷新成功！");
      } else {
        console.log("刷新失败！");
      }
    },

    *getMachineLineData({ payload: params }, { select, put, call }) {
      const res = yield call(machineService.getMachineLineData, params);
      if (res.code == "200") {
        yield put({ type: "updateState", payload: { machineInstanceRecord: res.data }});
      }
    },

    *getSystemMonitorData({ payload: params }, { select, put, call }) {
      const res = yield call(machineService.getSystemMonitorData, params);
      if (res.code == "200") {
        yield put({ type: "updateState", payload: { machineLineData: res.data }});
      }
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      const pathname = window.location.pathname;
      console.log("machineModel subscriptions setup pathname => ", pathname);
      if (pathname === "/resource/virtual") {
        dispatch({ type: 'getMachineList', payload: { currentPage: 1, pageSize: config.PAGE_SIZE }});
      }
    },
  },
};
